package com.grandtech.insurance.common.utils.collect;

import com.grandtech.insurance.common.db.jdbc.sql.ReflectUtil;
import com.grandtech.insurance.common.utils.ObjectUtil;

import java.util.List;
import java.util.Map;

/**
 * 关联两个实体
 *
 * @param <T>
 * @param <V>
 */
public class CollectJoin<T, V> {

    private T t;

    private V v;

    private List<T> left;

    private List<V> right;

    private Map<String, String> joinMap;

    private Map<String, Object> attrMap;

    public CollectJoin(List<T> left, List<V> right, Map joinMap, Map attrMap) {
        this.left = left;
        this.right = right;
        this.joinMap = joinMap;
        this.attrMap = attrMap;
    }

    public CollectJoin join(JoinType joinType) {
        boolean equal;
        if (joinType == JoinType.left) {
            for (int i = 0; i < left.size(); i++) {
                t = left.get(i);
                equal = false;
                for (int j = 0; j < right.size(); j++) {
                    v = right.get(j);
                    equal = ObjectUtil.objFieldsIsEqual(t, v, joinMap);
                    if (equal) break;
                }
                if (equal) ReflectUtil.setFieldValues(t, attrMap);
            }
        }
        if (joinType == JoinType.right) {
            for (int i = 0; i < right.size(); i++) {
                v = right.get(i);
                equal = false;
                for (int j = 0; j < left.size(); j++) {
                    t = left.get(i);
                    equal = ObjectUtil.objFieldsIsEqual(v, t, joinMap);
                    if (equal) break;
                }
                if (equal) ReflectUtil.setFieldValues(t, attrMap);
            }
        }
        return this;
    }

    public List<T> getLeft() {
        return left;
    }

    public List<V> getRight() {
        return right;
    }

    public enum JoinType {
        left,
        right
    }
}
